package com.hot100;

public class Solution84 {
    public int largestRectangleArea(int[] heights) {
        int n = heights.length;
        int[] minLeft = new int[n];
        minLeft[0] = -1;
        for (int i = 1; i < n; i++) {
            int t = i - 1;
            while (t >= 0 && heights[t] >= heights[i]) t = minLeft[t];
            minLeft[i] = t;
        }
        int[] minRight = new int[n];
        minRight[n - 1] = n;
        for (int i = n - 2; i >= 0; i--) {
            int t = i + 1;
            while (t < n && heights[t] >= heights[i]) t = minRight[t];
            minRight[i] = t;
        }
        int res = 0;
        for (int i = 0; i < n; i++) {
            int cur = heights[i] * (minRight[i] - minLeft[i] - 1);
            res = Math.max(res, cur);
        }
        return res;
    }
}
